﻿using DoDoveFramework;
using System.IO;
using cfg;
using Luban;
using SimpleJSON;
namespace Script
{
    public class GameConfigKit:Singleton<GameConfigKit>
    {
        public Tables gameConfig;

        private static string json_dir = "Assets/LubanData";
        
        public void InitGameConfigKit()
        {
            Initialize();
        }

        
        protected override void Initialize()
        {
            var tablesCtor = typeof(cfg.Tables).GetConstructors()[0];
            var loaderReturnType = tablesCtor.GetParameters()[0].ParameterType.GetGenericArguments()[1];
            System.Delegate loader = loaderReturnType == typeof(ByteBuf)
                ? new System.Func<string, ByteBuf>(LoadByteBuf)
                : (System.Delegate) new System.Func<string, JSONNode>(LoadJson);
            gameConfig = (cfg.Tables) tablesCtor.Invoke(new object[] {loader});
        }
        
        private static JSONNode LoadJson(string file)
        {
            return JSON.Parse(File.ReadAllText($"{json_dir}/{file}.json", System.Text.Encoding.UTF8));
        }

        private static ByteBuf LoadByteBuf(string file)
        {
            return new ByteBuf(File.ReadAllBytes($"{json_dir}/{file}.bytes"));
        }
    }
}